
package com.joolun.cloud.mall.api.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.joolun.cloud.common.core.constant.CacheConstants;
import com.joolun.cloud.common.core.util.R;
import com.joolun.cloud.common.data.tenant.TenantContextHolder;
import com.joolun.cloud.mall.api.service.PageDeviseService;
import com.joolun.cloud.mall.api.util.ApiUtil;
import com.joolun.cloud.mall.common.constant.MallConstants;
import com.joolun.cloud.mall.common.constant.MyReturnCode;
import com.joolun.cloud.mall.common.entity.PageDevise;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * 页面设计表
 *
 * @author www.joolun.com
 * @date 2020-09-22 13:38:09
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/pagedevise")
@Api(value = "pagedevise", tags = "页面设计API")
public class PageDeviseController {

    private final PageDeviseService pageDeviseService;
	private final RedisTemplate redisTemplate;

    /**
     * 页面设计表查询
     * @param pageDevise
     * @return R
     */
    @ApiOperation(value = "页面设计表查询")
    @GetMapping
    public R getById(HttpServletRequest request, PageDevise pageDevise) {
    	if(StrUtil.isBlank(pageDevise.getPageType())){
			return R.failed("pageType不能为空");
		}
		String clientType = ApiUtil.getClientType(request);
		if(MallConstants.DEVISE_PAGE_TYPE_1.equals(pageDevise.getPageType())){
			if(MallConstants.CLIENT_TYPE_H5_WX.equals(clientType)){
				clientType = MallConstants.CLIENT_TYPE_H5;
			}
			pageDevise.setClientType(clientType);
			pageDevise.setShopId("-1");
		}else if(MallConstants.DEVISE_PAGE_TYPE_2.equals(pageDevise.getPageType())){
			if(StrUtil.isBlank(pageDevise.getShopId())){
				return R.failed("shopId不能为空");
			}
			if(MallConstants.CLIENT_TYPE_H5_PC.equals(clientType)){
				pageDevise.setClientType(clientType);
			}else{
				pageDevise.setClientType("-1");
			}
		}

    	//先取缓存
		String key = StrUtil.format("{}:{}:{}:{}:{}",
				CacheConstants.MALL_PAGE_DEVISE_CACHE,
				TenantContextHolder.getTenantId(),
				pageDevise.getPageType(),
				pageDevise.getClientType(),
				pageDevise.getShopId());
		Object obj = redisTemplate.opsForValue().get(key);
		if(obj != null) {
			String str = String.valueOf(obj);
			pageDevise = JSONUtil.toBean(str, PageDevise.class);
		}else {
			pageDevise = pageDeviseService.getOne(Wrappers.query(pageDevise));
			if(pageDevise != null){
				//存入缓存
				redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(pageDevise),5, TimeUnit.DAYS);
			}
		}
		return R.ok(pageDevise);
    }

}
